//
//  UIWebView+Progress.m
//  UsedCar
//
//  Created by zhao on 9/24/15.
//  Copyright © 2015 易车网. All rights reserved.
//

#import "UIWebView+Progress.h"
#import <objc/runtime.h>

@implementation UIWebView (Progress)

#pragma mark - Public Method

- (void)progressViewAddInView:(UIView *)superView atFrame:(CGRect)frame {
    if (!self.progressView) {
        [self generateDefaultProgressView];
    }
    self.progressView.frame = frame;
    [superView addSubview:self.progressView];
}

- (void)didStartLoad {
    self.progressView.progress = 0;
    self.progressView.hidden   = false;
    [self.progressView setProgress:0.95 animated:true];
}

- (void)didFinishLoad {
    [self.progressView setProgress:1.0 animated:true];
    [self performSelector:@selector(clearProgress) withObject:nil afterDelay:0.5];
}

- (void)didFailLoadWithError {
    [self.progressView setProgress:1.0 animated:true];
    [self performSelector:@selector(clearProgress) withObject:nil afterDelay:0.5];
}

#pragma mark - 

- (void)generateDefaultProgressView {
    
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:
                                        CGRectMake(self.frame.origin.x,
                                                   self.frame.origin.y,
                                                   self.frame.size.width,
                                                   2)];
    progressView.progressTintColor = [UIColor orangeColor];
    progressView.trackTintColor    = [UIColor whiteColor];
    
    self.progressView = progressView;
}

- (void)clearProgress {
    self.progressView.hidden   = true;
    self.progressView.progress = 0;
}

static char ZBProgressView;

- (UIProgressView *)progressView {
    return objc_getAssociatedObject(self, &ZBProgressView);
}

- (void)setProgressView:(UIProgressView *)progressView {
    objc_setAssociatedObject(self, &ZBProgressView, progressView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

